<template>
  <a-drawer
    :title="title"
    :maskClosable="true"
    :width="drawerWidth"
    placement="right"
    :closable="true"
    @close="handleCancel"
    :visible="visible"
    style="height: 100%; overflow: auto; padding-bottom: 53px"
  >
    <template slot="title">
      <div style="width: 100%">
        <span>{{ title }}</span>
        <span style="display: inline-block; width: calc(100% - 51px); padding-right: 10px; text-align: right">
          <a-button @click="toggleScreen" icon="appstore" style="height: 20px; width: 20px; border: 0px"></a-button>
        </span>
      </div>
    </template>

    <a-spin :spinning="confirmLoading">
      <a-form-model
        ref="form"
        :model="doctor"
        :rules="validatorRules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        labelAlign="left"
      >
        <a-row type="flex">
          <a-col flex="30%">
            <p>上传头像</p>
            <div style="display: flex;flex-direction: column;align-items: center">
              <a-avatar class="avatar" :size="128" icon="user" :src="imageUrl" />
              <a-upload
                name="file"
                :showUploadList="false"
                :multiple="false"
                :action="uploadImgUrl"
                @change="handleImportImage"
              >
                <a-button class="upload" style="margin-top:50px" type="primary">选择</a-button>
              </a-upload>
            </div>

            <a-row>
              <a-col
                style="display: flex;
                      flex-direction: column;
                      align-items: center;"
              >
                <template v-if="doctor.qrcodeAddPatient">
                  <a-avatar
                    shape="square"
                    @click="reloadQrcode(1)"
                    :style="{ marginTop: '30px' }"
                    alt="添加患者二维码"
                    :size="128"
                    :src="doctor.qrcodeAddPatient"
                  />
                  <p :style="{ textAlign: 'center' }">添加患者二维码</p>
                </template>
                <template v-else>
                  <a-button type="primary" @click="reloadQrcode(1)" :style="{ marginTop: '15px' }"
                    >生成添加患者二维码</a-button
                  >
                </template>
              </a-col>
            </a-row>
            <a-row>
              <a-col
                style="display: flex;
                      flex-direction: column;
                      align-items: center;"
              >
                <template v-if="doctor.qrcodeAddTeam">
                  <a-avatar
                    shape="square"
                    @click="reloadQrcode(2)"
                    alt="添加团队成员二维码"
                    :size="128"
                    :src="doctor.qrcodeAddTeam"
                  />
                  <p :style="{ textAlign: 'center' }">添加团队成员二维码</p>
                </template>
                <template v-else>
                  <a-button type="primary" @click="reloadQrcode(2)" :style="{ marginTop: '15px' }"
                    >生成添加团队成员二维码</a-button
                  >
                </template>
              </a-col>
            </a-row>
          </a-col>
          <a-col flex="70%">
            <!-- <a-form-model ref="form" :model="model" :rules="validatorRules"> -->
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="姓名" prop="doctorsName">
                  <a-input style="width: 100%" placeholder="请输入姓名" :max-length="10" v-model="doctor.doctorsName" />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="性别" prop="doctorsSex">
                  <a-select
                    v-model="doctor.doctorsSex"
                    placeholder="请选择性别"
                    :getPopupContainer="target => target.parentNode"
                  >
                    <a-select-option :value="1">男</a-select-option>
                    <a-select-option :value="2">女</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="手机号码" prop="doctorsMobile">
                  <a-input style="width: 100%" placeholder="请输入手机号码" v-model="doctor.doctorsMobile" />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-spin :spinning="provinceLoading">
                  <a-form-model-item label="工作所在地" prop="doctorsCity">
                    <a-cascader
                      :options="options"
                      :load-data="loadData"
                      :default-value="doctorsCity"
                      placeholder="请选择工作所在地"
                      change-on-select
                      @change="onChangeAddress"
                      v-model="doctorsCity"
                    />
                  </a-form-model-item>
                </a-spin>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="出生日期">
                  <a-date-picker
                    :disabled-date="disabledDate"
                    v-model="doctor.doctorsBirthday"
                    placeholder="请选择出生日期"
                    @change="(date, dateString) => onChange(date, dateString, 'doctorsBirthday')"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="医院" prop="doctorsHospitalId">
                  <a-select v-model="doctor.doctorsHospitalId" :options="orgList" placeholder="请输入医生执业医院">
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="职称" prop="doctorsLevel">
                  <a-select v-model="doctor.doctorsLevel" :options="jobTitle" placeholder="请输入医生职称"> </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="执业经验" prop="doctorsTimeWork">
                  <a-date-picker
                    :disabled-date="disabledDate"
                    v-model="doctor.doctorsTimeWork"
                    placeholder="开始从业时间"
                    @change="(date, dateString) => onChange(date, dateString, 'doctorsTimeWork')"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col>
                <a-form-model-item label="医生经历" :labelCol="areaLabelCol" :wrapperCol="areaWrapperCol">
                  <a-textarea
                    v-model="doctor.doctorsWorkExperience"
                    :max-length="500"
                    placeholder="请输入医生经历，500字以内"
                    :auto-size="{ minRows: 5, maxRows: 8 }"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col>
                <a-form-model-item label="职业专长" :labelCol="areaLabelCol" :wrapperCol="areaWrapperCol">
                  <a-textarea
                    v-model="doctor.doctorsSpecialSkill"
                    :max-length="500"
                    placeholder="请输入职业专长，500字以内"
                    :auto-size="{ minRows: 5, maxRows: 8 }"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row v-if="doctor.doctorsWorkCard">
              <a-col>
                <a-form-model-item label="工作证" :labelCol="areaLabelCol">
                  <p>要求所在医院的工作证件</p>
                  <img
                    class="img"
                    style="width:150px;height:150px;display:inline-block"
                    :src="doctor.doctorsWorkCard"
                    @click="handlePreview(doctor.doctorsWorkCard)"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row v-else>
              <a-col>
                <a-form-model-item label="工作证" :labelCol="areaLabelCol">
                  <p>未上传工作证</p>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row v-if="doctor.doctorsProfessionImg">
              <a-col>
                <a-form-model-item label="职称证" :labelCol="areaLabelCol">
                  <p>要求带有职称、资格级别的资格证件</p>
                  <img
                    class="img"
                    style="width:150px;height:150px;display:inline-block"
                    :src="doctor.doctorsProfessionImg"
                    @click="handlePreview(doctor.doctorsProfessionImg)"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row v-else>
              <a-col>
                <a-form-model-item label="职称证" :labelCol="areaLabelCol">
                  <p>未上传职称证</p>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row v-if="doctorsCertificate && doctorsCertificate.length > 0">
              <a-col>
                <a-form-model-item label="执业证" :labelCol="areaLabelCol">
                  <p>需提供证件第一页和第二页</p>
                  <template v-for="item in doctorsCertificate">
                    <img
                      class="img"
                      style="width:150px;height:150px;display:inline-block;margin-right:10px"
                      :src="item"
                      :key="item"
                      @click="handlePreview(item)"
                    />
                  </template>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row v-else>
              <a-col>
                <a-form-model-item label="执业证" :labelCol="areaLabelCol">
                  <p>未上传执业证</p>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row v-if="doctorsWorkPermits && doctorsWorkPermits.length > 0">
              <a-col>
                <a-form-model-item label="资格证" :labelCol="areaLabelCol">
                  <p>需提供证件第一页和第二页</p>
                  <template v-for="item in doctorsWorkPermits">
                    <img
                      class="img"
                      style="width:150px;height:150px;display:inline-block;margin-right:10px"
                      :src="item"
                      :key="item"
                      @click="handlePreview(item)"
                    />
                  </template>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row v-else>
              <a-col>
                <a-form-model-item label="资格证" :labelCol="areaLabelCol">
                  <p>未上传资格证</p>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-modal
              :visible="previewable"
              :width="700"
              :footer="null"
              :closable="true"
              :centered="true"
              @cancel="() => (previewable = false)"
            >
              <img :src="previewUrl" style="width:600px;height:400px" />
            </a-modal>
            <a-row v-if="status !== null">
              <a-col>
                <a-form-model-item v-if="status == 2" label="审核结果" :labelCol="areaLabelCol" prop="doctorsIsverify">
                  <a-radio-group v-model="doctor.doctorsIsverify">
                    <a-radio :value="1"> 通过 </a-radio>
                    <a-radio :value="3"> 不通过 </a-radio>
                  </a-radio-group>
                  <a-input
                    v-if="doctor.doctorsIsverify == '3'"
                    type="textarea"
                    placeholder="请输入审核未通过原因(50字内)"
                    v-model="doctor.remark"
                  />
                </a-form-model-item>
                <a-form-model-item v-if="status != 2" label="审核结果" :labelCol="areaLabelCol">
                  <p v-if="status == 1">通过</p>
                  <div v-if="status == 3">
                    <p>不通过  <a-button type="primary" style="margin-left: 10px" size="small" @click="passVerify">通过</a-button> </p>
                  </div>
                </a-form-model-item>
                <a-form-model-item v-if="status == 3" label="不通过原因" :labelCol="areaLabelCol">
                  <p>{{ doctor.remark }}</p>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col>
                <a-form-model-item> </a-form-model-item>
              </a-col>
            </a-row>
            <!-- </a-form-model> -->
          </a-col>
        </a-row>
      </a-form-model>
    </a-spin>

    <div class="drawer-bootom-button" v-show="!disableSubmit">
      <a-popconfirm title="确定放弃编辑？" @confirm="handleCancel" okText="确定" cancelText="取消">
        <a-button style="margin-right: 0.8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="confirmLoading">提交</a-button>
    </div>
  </a-drawer>
</template>

<script>
import { PAGE_MENU_TYPE } from '@/store/mutation-types'
import { postAction, getAction } from '@/api/manage'
import { getDictItemsFromCache } from '@/api/api'
import moment from 'moment'

export default {
  name: 'TeamDoctorModal',
  components: {},
  props: ['isEdit'],
  data() {
    return {
      drawerWidth: 1000,
      disableSubmit: false,
      provinceLoading: true,
      title: '操作',
      visible: false,
      doctor: {},
      doctorsCertificate: [],
      doctorsWorkPermits: [],
      options: [],
      imageUrl: '',
      doctorsIsverify: '',
      remark: '',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 }
      },
      areaLabelCol: {
        xs: { span: 24 },
        sm: { span: 4 }
      },
      areaWrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 }
      },
      doctorsCity: [],
      orgList: [],
      jobTitle: [],
      status: null,
      uploadLoading: false,
      confirmLoading: false,
      validatorRules: {
        doctorsName: [{ required: true, message: '请输入姓名!' }],
        doctorsSex: [{ required: true, message: '请选择性别!' }],
        doctorsMobile: [{ required: true, message: '请输入手机号码!' }, { validator: this.isRightMobileNumber }],
        doctorsHospitalId: [{ required: true, message: '请输入医生执业医院!' }],
        // doctorsDepartment: [{ required: true, message: '请输入医生所属科室!' }],
        doctorsLevel: [{ required: true, message: '请输入医生职称!' }],
        doctorsTimeWork: [{ required: true, message: '请选择日期!' }],
        doctorsIsverify: [{ validator: this.isverify }]
      },
      url: {
        doctorDetail: '/201/02/2010201',
        addDoctor: '/201/02/2010204',
        modifyDoctor: '/201/02/2010202',
        imgUrl: '/sys/common/upload',
        createQrcode: '/201/02/2010221'
      },
      previewUrl: '',
      previewable: false
    }
  },
  computed: {
    uploadImgUrl() {
      return `${window._CONFIG['domianURL']}/${this.url.imgUrl}`
    }
  },
  watch: {
    doctorsCity(n) {
      if (n.length < 2) return
      this.doctor.doctorsProvinceId = n[0]
      this.doctor.doctorsCityId = n[1]
      const list = this.options
      let str = ''
      list.forEach(v => {
        if (n[0] == v.value) {
          str += v.label
          v.children &&
            v.children.forEach(item => {
              if (n[1] == item.value) {
                str += item.label
              }
            })
        }
      })
      this.doctor.doctorsCity = str
    }
  },
  created() {
    this.getProvince()
    this.handleGetLevel()
  },
  methods: {
    getDetail(params) {
      postAction(this.url.doctorDetail, params).then(res => {
        if (res.success) {
          this.doctor = res.result
          this.imageUrl = res.result.doctorsImg
          // this.doctor.doctorsTimeWork = moment(res.result.doctorsTimeWork)
          // console.log(this.doctor.doctorsTimeWork, 'this.doctor.doctorsTimeWork')
          if (res.result.doctorsProvinceId) {
            this.doctorsCity = [res.result.doctorsProvinceId]
            const index = this.options.findIndex(v => {
              return v.value == res.result.doctorsProvinceId
            })
            this.loadData([this.options[index]])
          }
          this.doctorsCity = [res.result.doctorsProvinceId, res.result.doctorsCityId]
          res.result.doctorsCertificate && (this.doctorsCertificate = res.result.doctorsCertificate.split(','))
          res.result.doctorsWorkPermits && (this.doctorsWorkPermits = res.result.doctorsWorkPermits.split(','))
        }
      })
    },
    handleGetLevel() {
      getAction('/sys/sysDepart/queryTreeList').then(res => {
        console.log('handleGetLevel', res)
        if (res.success) {
          this.orgList = res.result[0].children.map(v => {
            return {
              title: v.title,
              text: v.title,
              value: v.orgCode
            }
          })
        }
      })
      this.jobTitle = getDictItemsFromCache('jobTitle')
    },
    add() {
      this.edit()
    },
    edit(record) {
      if (record && record.id) {
        this.getDetail({ doctorId: record.id, mobile: record.doctorsMobile })
        this.status = record.doctorsIsverify
      }
      this.visible = true
      this.resetScreenSize()
    },
    // 根据屏幕变化,设置抽屉尺寸
    resetScreenSize() {
      let screenWidth = document.body.clientWidth
      if (screenWidth < 500) {
        this.drawerWidth = screenWidth
      } else {
        this.drawerWidth = 1000
      }
    },
    //窗口最大化切换
    toggleScreen() {
      if (this.modaltoggleFlag) {
        this.modalWidth = window.innerWidth
      } else {
        this.modalWidth = 800
      }
      this.modaltoggleFlag = !this.modaltoggleFlag
    },
    isRightMobileNumber(rule, value, callback) {
      if (typeof value === 'undefined' || value === '') {
        callback()
      } else {
        const regex = /^1[3456789]\d{9}$/
        if (!regex.test(value)) {
          callback(new Error('手机号码格式错误！'))
        }
        callback()
      }
    },
    handlePreview(url) {
      this.previewUrl = url
      this.previewable = true
    },
    isverify(rule, value, callback) {
      if (typeof this.doctor.doctorsIsverify === 'undefined' || this.doctor.doctorsIsverify === '') {
        callback(new Error('请选择审核结果！'))
      } else {
        if (this.doctor.doctorsIsverify == '3' && !this.doctor.remark) {
          callback(new Error('请输入审核未通过原因！'))
        } else {
          callback()
        }
      }
    },
    getProvince() {
      getAction('/dict/district/province')
        .then(res => {
          if (res.success) {
            this.options = res.result.map(v => {
              return {
                value: v.districtId,
                label: v.name,
                isLeaf: false
              }
            })
          }
        })
        .finally(_ => {
          this.provinceLoading = false
        })
    },
    handleSubmit() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          that.confirmLoading = true
          this.orgList.forEach(v => {
            if (this.doctor.doctorsHospitalId == v.value) {
              this.doctor.doctorsHospital = v.title
              this.doctor.orgCode = v.value
            }
          })
          if (this.isEdit) {
            // 编辑
            postAction(this.url.modifyDoctor, this.doctor).then(res => {
              if (res.success) {
                that.$message.success('操作成功')
                this.$emit('ok')
                this.handleCancel()
              } else {
                that.$message.error(res.message)
              }
            }).finally(_ => {
              that.confirmLoading = false
            })
            // }
          } else {
            // 新建
            postAction(this.url.modifyDoctor, this.doctor).then(res => {
              // 新建编辑同一接口
              if (res.success) {
                that.$message.success('操作成功')
                this.$emit('ok')
                this.handleCancel()
              } else {
                that.$message.error(res.message)
              }
            }).finally(_ => {
              that.confirmLoading = false
            })
          }
        } else {
          return false
        }
      })
    },
    passVerify() {
      this.doctor.doctorsIsverify = 1
      postAction(this.url.modifyDoctor, this.doctor).then(res => {
        if (res.success) {
          this.$message.success('操作成功')
          this.$emit('ok')
          this.handleCancel()
        } else {
          this.$message.error(res.message)
        }
      }).finally(_ => {
        this.confirmLoading = false
      })
    },
    handleCancel() {
      this.confirmLoading = false
      this.visible = false
      this.disableSubmit = false
      this.imageUrl = ''
      this.doctorsIsverify = ''
      this.remark = ''
      this.doctorsCity = []
      this.doctorsCertificate = []
      this.doctorsWorkPermits = []
      // this.$refs.form.resetFields()
      this.doctor = {}
      this.$emit('cancel', false)
    },
    onChangeAddress(value) {
      // console.log(value, 'value')
    },
    loadData(selectedOptions) {
      console.log(selectedOptions)
      const targetOption = selectedOptions[selectedOptions.length - 1]
      // targetOption.loading = true;
      getAction('/dict/district/city', {
        provinceId: targetOption.value
      }).then(res => {
        if (res.success) {
          // this.cityList = res.result
          targetOption.children = res.result.map(v => {
            return {
              value: v.districtId,
              label: v.name
            }
          })
          this.options = [...this.options]
        }
      })
      //   .finally(_ => {
      //     // targetOption.loading = false
      //   })
    },
    handleImportImage(info) {
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          this.imageUrl = info.file.response.message
          this.doctor.doctorsImg = this.imageUrl
        }
        //this.$message.success(`${info.file.name} 上传成功!`);
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 上传失败.`)
      }
    },
    onChange(date, dateString, field) {
      this.doctor[field] = dateString
    },
    disabledDate(current) {
      return current > moment().endOf('day')
    },
    reloadQrcode(type) {
      getAction(this.url.createQrcode, {
        doctorId: this.doctor.dataId,
        qrCodeType: type
      }).then(res => {
        if (res.success) {
          if (type == 1) {
            this.doctor.qrcodeAddPatient = res.result
          } else {
            this.doctor.qrcodeAddTeam = res.result
          }
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.avatar {
  display: block;
  margin-top: 50px;
}
/deep/.ant-upload {
  display: block;
  text-align: center;
}
/deep/.ant-col-sm-4 {
  width: 14.67%;
}
.drawer-bootom-button {
  position: absolute;
  bottom: -8px;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
}
.img:hover {
  cursor: pointer;
}
</style>

